<template>
  <MesBox
    title="生成采购单"
    v-model="visible"
    :width="1200"
    :height="600"
    :onModelClose="onModelClose"
  >
    <MesForm
      ref="sendForm"
      :formFields="formFields"
      :formRules="formRules"
    ></MesForm>
    <MesTable
      :tableData="sendTableData"
      :columns="sendColumns"
      :clickEdit="true"
      :index="true"
      :ck="false"
    ></MesTable>
    <template #footer>
      <el-button type="danger" @click="saveData">
        <i class="el-icon-check"></i>
        保存</el-button
      >
    </template>
  </MesBox>
</template>

<script setup>
import MesBox from '@/components/basic/MesBox.vue'
import MesForm from '@/components/basic/MesForm.vue'
import MesTable from '@/components/basic/MesTable.vue'
import { getCurrentInstance, ref } from 'vue'
import { useRoute } from 'vue-router'
import { getNowDate } from '@/uitils/dateFormatUtil'

const emit = defineEmits(['parentCall'])
const route = useRoute()
const that = getCurrentInstance().appContext.config.globalProperties
const sendForm = ref(null)
let url = ''
let visible = ref(false)
let sendTableData = ref([])
let formFields = ref({
  MoCode: '',
  CreateTime: '',
  CreateUser: '',
  Supplier: '',
  Currency: 'CNY',
  ExchangeRate: '1',
  Price: '',
  TaxRate: '1.13',
})
let formRules = [
  [
    {
      title: '订单号',
      field: 'MoCode',
      readonly: true,
    },
    {
      title: '采购时间',
      field: 'CreateTime',
      type: 'datetime',
      required: true,
    },
  ],
  [
    // {
    //   title: '采购人',
    //   field: 'CreateUser',
    //   required: true,
    // },
    {
      title: '供应商',
      field: 'Supplier',
      type: 'select',
      dataKey: 'Supplier',
      required: true,
    },
    {
      title: '汇率',
      field: 'ExchangeRate',
      type: 'decimal',
      required: true,
      disabled: true,
    },
  ],
  [
    {
      title: '币别',
      field: 'Currency',
      required: true,
      type: 'select',
      dataKey: 'Currency',
      disabled: true,
    },
    {
      title: '税率',
      field: 'TaxRate',
      required: true,
      type: 'select',
      dataKey: 'taxrate',
      onChange: () => {
        sendTableData.value = sendTableData.value.map((item) => {
          if (item.Price) {
            return {
              ...item,
              UnitPrice: '',
              Price: '',
            }
          }
          return item
        })
      },
    },
  ],
]

const sendColumns = [
  {
    title: '物料编号',
    field: 'InvCode',
  },
  {
    title: '物料名称',
    field: 'InvName',
  },
  {
    title: '物料规格',
    field: 'InvStandard',
  },
  {
    title: '计划采购数量',
    field: 'Qty',
  },
  {
    title: '实际采购数量',
    field: 'ActualQty',
    edit: {
      type: 'number',
      min: 0,
    },
    required: true,
  },
  {
    title: '未税单价',
    field: 'Price',
    edit: {
      type: 'decimal',
      min: 0,
    },
    required: true,
    onKeyPress: (row, column, $event) => {
      // console.log(row)
      let price = Number(row.Price)
      let parsePrice = parseFloat(row.Price)
      if (formFields.value.TaxRate == '' || formFields.value.TaxRate == null) {
        that.$message.error('请先选择税率')
        return
      }
      if (price !== price) {
        console.log(row.Price)
        if (row.Price.indexOf('NaN') !== -1) {
          row.Price = ''
        } else {
          row.Price = parsePrice
          that.$message.error('请输入数字')
          return
        }
      }
      let decimal = (price + '').split('.')[1]
      let integer = (price + '').split('.')[0]
      if (decimal && decimal.length > 4) {
        row.Price = integer + '.' + decimal.substring(0, 4)
        return that.$message.error('最多支持4位小数')
      }

      //未税单价*税率=含税单价
      row.UnitPrice = (price * Number(formFields.value.TaxRate)).toFixed(2)
    },
  },
  {
    title: '含税单价',
    field: 'UnitPrice',
    edit: {
      type: 'decimal',
      min: 0,
    },
    required: true,
    onKeyPress: (row, column, $event) => {
      let unitPrice = Number(row.UnitPrice)
      let parsePrice = parseFloat(row.UnitPrice)
      if (formFields.value.TaxRate == '' || formFields.value.TaxRate == null) {
        that.$message.error('请先选择税率')
        return
      }
      if (unitPrice !== unitPrice) {
        if (row.UnitPrice.indexOf('NaN') !== -1) {
          row.UnitPrice = ''
        } else {
          row.UnitPrice = parsePrice
          that.$message.error('请输入数字')
          return
        }
      }
      let decimal = (unitPrice + '').split('.')[1]
      let integer = (unitPrice + '').split('.')[0]
      if (decimal && decimal.length > 2) {
        row.UnitPrice = integer + '.' + decimal.substring(0, 4)
        return that.$message.error('最多支持2位小数')
      }

      //含税单价/税率=未税单价
      row.Price = (unitPrice / Number(formFields.value.TaxRate)).toFixed(4)
    },
  },
  {
    title: '交货日期',
    field: 'DeliveryDate',
    required: true,
    edit: {
      type: 'datetime',
    },
  },
]
const onModelClose = () => {
  for (let key in formFields.value) {
    formFields.value[key] = ''
  }
  sendTableData.value = []
}
//保存
const saveData = () => {
  sendForm.value.validate(async (valid) => {
    if (valid) {
      try {
        sendTableData.value.some((item) => {
          // console.log(item)
          if (!item.ActualQty) {
            throw new Error('请输入实际采购数量')
          }

          if (Number(item.ActualQty) !== Number(item.ActualQty)) {
            throw new Error('实际采购数量中间不能有特殊字符')
          }

          if (typeof item.ActualQty == 'string') {
            if (item.ActualQty.indexOf('.') !== -1) {
              throw new Error('实际采购数量只能是整数')
            }
          }

          if (!item.Price) {
            throw new Error('请输入单价')
          }

          if (Number(item.Price) !== Number(item.Price)) {
            throw new Error('单价中间不能有特殊字符')
          }

          if (!item.DeliveryDate) {
            throw new Error('请输入交货日期')
          }
        })

        let moCode = formFields.value.MoCode
        let list = sendTableData.value.map((item) => {
          if (route.path == '/Production_AtherLackStock') {
            // console.log(item)
            return {
              id: item.AtherLackList_Id,
              currency: formFields.value.Currency,
              exchangeRate: formFields.value.ExchangeRate,
              supplier: formFields.value.Supplier,
              price: item.Price,
              taxRate: formFields.value.TaxRate,
              unitPrice: item.UnitPrice,
              qty: item.ActualQty,
              deliveryDate: item.DeliveryDate,
            }
          } else {
            return {
              invName: item.invName,
              reqList_Id: item.ReqList_Id,
              qty: item.ActualQty,
              currency: formFields.value.Currency,
              exchangeRate: formFields.value.ExchangeRate,
              supplier: formFields.value.Supplier,
              price: item.Price,
              taxRate: formFields.value.TaxRate,
              unitPrice: item.UnitPrice,
              deliveryDate: item.DeliveryDate,
            }
          }
        })

        let res = null
        if (route.path == '/Production_AtherLackStock') {
          url = '/api/Production_AtherLackStock/BatchVerifyAtherLackStock'
          res = await that.http.post(url, list, true)
        } else {
          url = '/api/Production_Requisition/BatchVerify'
          res = await that.http.post(
            url,
            [
              {
                moCode,
                list,
              },
            ],
            true
          )
        }

        if (res.status) {
          that.$message.success('保存成功')
          for (let key in formFields.value) {
            formFields.value[key] = ''
          }
          formFields.value.ExchangeRate = 1
          formFields.value.CreateTime = getNowDate()
          visible.value = false
          if (route.path == '/Production_AtherLackStock') {
            emit('parentCall', ($parent) => {
              $parent.search()
            })
          } else {
            emit('parentCall')
          }
        } else {
          that.$message.error(res.message)
        }
      } catch (error) {
        that.$message.error(error.message)
        console.log(error)
      }
    }
  })
}

const openModel = () => {
  visible.value = true
}

const setFormFields = (fields) => {
  Object.keys(fields).forEach((key) => {
    // console.log(key, fields[key]);
    formFields.value[key] = fields[key]
  })
}

const setSendTableData = (data) => {
  sendTableData.value = data
}

defineExpose({ openModel, setFormFields, setSendTableData })
</script>

<style lang="scss" scoped></style>
